<template>
	<view class="content">

		<cu-custom bgColor="bg-gradual-blue" :isBack="false">
			<block slot="backText"></block>
			<block slot="content">{{i18n.title}}</block>
		</cu-custom>

		<form id="formEmplotee" @submit="formSubmit">

			<view style="height: 60upx;align-items: center;display: flex;margin-left: 28upx;">Visitor Info</view>

			<view class="cu-form-group">
				<view class="title">{{i18n.name}}<span style="color:red">*</span></view>
				<input class="input-right" :placeholder="i18n.nameHint" name="name"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">{{i18n.phone}}<span style="color:red">*</span>
				</view>
				<view @tap="showPicker('pCode')">
					+{{pCode}}<text class="cuIcon-triangledownfill"></text>
				</view>
				<input type="number" class="input-right" :placeholder="i18n.phone" name="phone"></input>
			</view>
			<view class="cu-bar bg-white solid-top">
				<view class="action">
					{{i18n.selectFace}}<span style="color:red">*</span>
				</view>
				<view class="action">
					0/1
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
						<image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<1">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">Certificate Type<span style="color:red">*</span></view>
				<view @tap="showPicker('cType')">
					{{cType}}<text class="cuIcon-right"></text>
				</view>
			<!-- 	<picker v-if="cTypeList.length>0" @change="bindPickerChange" :value="typeIndex" range-key="typename" :range="cTypeList">
					<view class="picker">
						{{cTypeList[typeIndex].typename}}
					</view>
				</picker> -->
			</view>
			<view class="cu-form-group">
				<view class="title">Certificate Number<span style="color:red">*</span></view>
				<input type="number" placeholder="Certificate Number" class="input-right" name="cNumber"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">Company</view>
				<input type="text" placeholder="Company" class="input-right" name="company"></input>
			</view>
			<view class="cu-bar bg-white solid-top">
				<view class="action">
					Person ID Photo(ID/Passport/Driver license)<span style="color:red">*</span>
				</view>
				<view class="action">
					0/1
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-3 grid-square flex-sub">
					<view class="bg-img" style="width: 380upx;" v-for="(item,index) in idCardImgList" :key="index" @tap="ViewIDCardImage"
					 :data-url="idCardImgList[index]">
						<image :src="idCardImgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelIDCardImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view style="width: 380upx;" class="solids" @tap="selectIDCard" v-if="idCardImgList.length<1">
						<text class='cuIcon-newsfill'></text>
					</view>
				</view>
			</view>

			<view style="height: 60upx;align-items: center;display: flex;margin-left: 28upx;">Host Info</view>

			<view class="cu-form-group">
				<view class="title">Host Name<span style="color:red">*</span></view>
				<input type="text" class="input-right" placeholder="Host Name" name="hostName"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">Host Phone<span style="color:red">*</span></view>
				<view @tap="showPicker('hCode')">
					+{{hCode}}<text class="cuIcon-triangledownfill"></text>
				</view>
				<input type="number" class="input-right" placeholder="Host Phone" name="hostPhone"></input>
			</view>
			<view class="cu-form-group align-start margin-top">
				<view class="response">
					<view class="title">{{i18n.reason}}</view>
					<textarea name="reason" maxlength="-1" :placeholder="i18n.reasonHint"></textarea>
				</view>
			</view>

			<view @click="ChoiceTime('start')" class="cu-form-group margin-top">
				<view class="title">{{$t('startTime')}}<span style="color:red">*</span></view>
				<text style="padding-right: 25upx;">{{starttime.title}}</text>
			</view>
			<view @click="ChoiceTime('end')" class="cu-form-group">
				<view class="title">{{$t('endTime')}}<span style="color:red">*</span></view>
				<text style="padding-right: 25upx;">{{endtime.title}}</text>
			</view>

			<view class="padding">
				<button :disabled="loadding" style="background-color: #5599FF;" :loading="loadding" type="primary" form-type="submit">{{$t('sure')}}</button>
				<button v-show="false" ref="resrtBtn" style="background-color: #5599FF;" type="default" form-type="reset"></button>
			</view>
		</form>
		<select-date :name="choicename" @complete="TimeComplete" :timetype="timetype" :open="opendate" @change="SelectChange"></select-date>
		<w-picker
			mode="selector"
			value="62"
			default-type="tel"
			:default-props="defaultProps"
			:options="codeList"
			@confirm="onConfirm($event,'pCode')"
			@cancel="onCancel"
			ref="pCode" 
		></w-picker>
		<w-picker
			mode="selector"
			value="62"
			default-type="tel"
			:default-props="defaultProps"
			:options="codeList"
			@confirm="onConfirm($event,'hCode')"
			@cancel="onCancel"
			ref="hCode" 
		></w-picker>
		<w-picker
			mode="selector"
			:default-props="cdefaultProps"
			:options="cTypeList"
			@confirm="onConfirm($event,'cType')"
			@cancel="onCancel"
			ref="cType" 
		></w-picker>
	</view>
</template>

<script>
	var _self;
	var globalData = null;
	import selectDate from '@/components/selectdate/selectdate.vue'
	import areacode from '../../common/areacode.js'
	import wPicker from "@/components/w-picker/w-picker.vue"
	import {
		pathToBase64,
		base64ToPath
	} from '@/components/image-tools/index.js'
	export default {
		computed: {
			i18n() {
				return this.$t('visitor')
			},
		},
		components: {
			selectDate,
			wPicker
		},
		data() {
			return {
				index: -1,
				imgList: [],
				idCardImgList: [],
				idCardImgBase64: '',
				loadding: false,
				choicename: 'start',
				opendate: false,
				timetype: 'hour',
				starttime: {
					title: this.$t('leave').selectTips,
					timestamp: 0,
					time: ''
				},
				imgurl: '',
				endtime: {
					title: this.$t('leave').selectTips,
					timestamp: 0,
					time: ''
				},
				cTypeList: [],
				cType: '',
				cTypeValue:'',
				pCode:'62',
				hCode:'62',
				codeList:[],
				defaultProps:{
					label:"show",
					value:"tel",
				},
				cdefaultProps:{
					label:"typename",
					value:"typecode",
				},
			}
		},
		onShow() {
			// var pages = getCurrentPages();
			// var currPage = pages[pages.length - 1]
			// console.log('imgurl',this.imgurl)
			// if (typeof(currPage.imgurl) != 'undefined' && currPage.imgurl != '') {
			// 	this.$set(this.imgList, 0, currPage.imgurl);
			// }
		},
		onLoad(options) {
			this.codeList = areacode.code
			var codeList = areacode.code
			codeList.forEach(function(item){
				item.show = item.name + '(+'+item.tel + ')'
			})
			_self = this;
			this.getCtype()
			//获取当前时间
			var nowDate = new Date()
			var year = nowDate.getFullYear()
			var month = nowDate.getMonth() + 1
			month = month < 10 ? '0' + month : month
			var day = nowDate.getDate()
			day = day < 10 ? '0' + day : day
			var hour = nowDate.getHours()
			hour = hour < 10 ? '0' + hour : hour
			var minute = nowDate.getMinutes()
			var nowTime = year + "-" + month + "-" + day + " " + hour + ":00:00"
			var nowTitle = year + "-" + month + "-" + day + " " + hour + ":00"
			var timestamp = nowDate.getTime()
			var endTime = year + "-" + month + "-" + day + " " + "23:59:59"
			var endTimeTitle = year + "-" + month + "-" + day + " " + "23:59"
			this.starttime = {
				title: nowTitle,
				time: nowTime,
				timestamp: timestamp
			}
			this.endtime = {
				title: endTimeTitle,
				time: endTime,
				timestamp: timestamp
			}

			globalData = getApp().globalData
			this.sysCompanyCode = options.sysCompanyCode
			// this.sysCompanyCode = 'A04'
			console.log(options)
		},
		methods: {
			getCtype() {
				uni.request({
					url: _self.$constant.BASEURL + _self.$constant.GET_CERTIFICATE_TYPE,
					// url: "http://192.168.0.116:8080/" + _self.$constant.GET_CERTIFICATE_TYPE,
					method: "POST",
					data: {},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log(res.data);
						if (res.data.code == 0) {
							this.cTypeList = res.data.data.certitype
							this.cType = this.cTypeList[0].typename
							this.cTypeValue = this.cTypeList[0].typecode
						}
					}
				});
			},
			showPicker(type,id){
				this.$refs[type].show();
			},
			onConfirm(res,type){
				console.log(res)
				if(type == 'pCode'){
					this.pCode = res.value
				}
				if(type == 'hCode'){
					this.hCode = res.value
				}
				if(type == 'cType'){
					this.cType = res.result
					this.cTypeValue = res.value
				}
			},
			onCancel(){
				
			},
			SelectChange(e) {
				if (!e.show) {
					this.opendate = false
				}
			},
			ChoiceTime(type) {
				this.opendate = true
				this.choicename = type
			},
			TimeComplete(e) {
				if (e.name == 'start') {
					this.starttime = e.date
				} else {
					this.endtime = e.date
				}
				// console.log(e)
			},
			ChooseImage() {
				// this.$router.push('../camera/camera');
				uni.navigateTo({
					url: '../camera/camera'
				})
			},
			// bindPickerChange(e) {
			// 	this.typeIndex = e.target.value
			// },
			ViewImage(e) {
				uni.previewImage({
					urls: _self.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			ViewIDCardImage(e) {
				uni.previewImage({
					urls: _self.idCardImgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: this.$t('notice'),
					content: this.i18n.delImgTips,
					cancelText: this.i18n.cancel,
					confirmText: this.i18n.confirm,
					success: res => {
						if (res.confirm) {
							_self.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			DelIDCardImg(e) {
				uni.showModal({
					title: this.$t('notice'),
					content: this.i18n.delImgTips,
					cancelText: this.i18n.cancel,
					confirmText: this.i18n.confirm,
					success: res => {
						if (res.confirm) {
							_self.idCardImgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			checkPhone(number) {
				return true
			},
			selectIDCard() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						_self.$set(_self.idCardImgList, 0, res.tempFilePaths[0]);
						pathToBase64(_self.idCardImgList[0])
							.then(base64 => {
								_self.idCardImgBase64 = base64
							})
					}
				})
			},
			formSubmit(e) {
				var res = e.detail.value
				if (res.name == '') {
					uni.showToast({
						title: this.i18n.nameHint,
						icon: 'none'
					})
					return
				}

				if (res.phone == '') {
					uni.showToast({
						title: this.i18n.phoneHint,
						icon: 'none'
					})
					return
				} else if (!_self.checkPhone(res.phone)) {
					uni.showToast({
						title: this.i18n.phoneError,
						icon: 'none'
					})
					return
				}
				
				let phoneNum = parseInt(res.phone)
				let phoneStr = _self.pCode + String(phoneNum)
				
				if (!_self.imgList.length > 0) {
					uni.showToast({
						title: this.i18n.selectFace,
						icon: 'none'
					})
					return
				}

				if (res.cNumber == '') {
					uni.showToast({
						title: "Input Certificate Number",
						icon: 'none'
					})
					return
				}


				if (!_self.idCardImgList.length > 0) {
					uni.showToast({
						title: 'Upload Person ID Photo',
						icon: 'none'
					})
					return
				}

				if (res.hostName == '') {
					uni.showToast({
						title: "Input Host Name",
						icon: 'none'
					})
					return
				}

				if (res.hostPhone == '') {
					uni.showToast({
						title: "Input Host Phone",
						icon: 'none'
					})
					return
				}
				
				let hostPhoneNum = parseInt(res.hostPhone)
				let hostPhoneStr = _self.hCode + String(hostPhoneNum)

				if (_self.starttime.timestamp == 0) {
					
					uni.showToast({
						title: this.i18n.startTimeHint,
						icon: 'none'
					})
					return
				}

				if (_self.endtime.timestamp == 0) {
					uni.showToast({
						title: this.i18n.endTimeHint,
						icon: 'none'
					})
					return
				}

				if (new Date(_self.starttime.time) > new Date(_self.endtime.time)) {
					uni.showToast({
						title: this.i18n.timeToMast,
						icon: 'none'
					})
					return
				}

				if (res.hostPhone == '') {
					uni.showToast({
						title: this.i18n.toBePhoneHint,
						icon: 'none'
					})
					return
				}

				if (!_self.checkPhone(res.hostPhone)) {
					uni.showToast({
						title: this.i18n.toBePhoneError,
						icon: 'none'
					})
					return
				}
				
				let formData = {
					//访客
					vname: res.name, //姓名
					vphone: phoneStr, //手机号
					certificatetype: _self.cTypeValue, //证件类型
					certificatenumber: res.cNumber, //证件号码
					comecompany: res.company, //公司
					certificatephoto: _self.idCardImgBase64, //证件照片
					//受访人
					hostname: res.hostName, //受访人
					tophone: hostPhoneStr, //受访人手机号
					vdesc: res.reason, //原因
					sdate: _self.starttime.time, //开始时间
					edate: _self.endtime.time, // 结束时间
					sysCompanyCode: this.sysCompanyCode
				}

				console.log(formData)
				_self.loadding = true

				uni.uploadFile({
					url: _self.$constant.BASEURL + _self.$constant.ADD_VISITOR,
					// url: "http://192.168.0.116:8080/"  + _self.$constant.ADD_VISITOR,
					filePath: _self.imgList[0],
					name: 'personphotos',
					formData: formData,
					success: (res) => {
						console.log(res)
						var result = JSON.parse(res.data.toString())
						if (result.code == 0) {
							uni.showModal({
								title: _self.$t('notice'),
								content: _self.i18n.successTips,
								cancelText: this.$t('sure'),
								confirmText: this.$t('cancel')
							})
							//清空form表单
							_self.$refs.resrtBtn.$dispatch('Form', 'uni-form-reset', {
								type: 'reset'
							})
							_self.imgList = []
						} else {
							uni.showToast({
								title: result.message,
								icon: 'none'
							})
						}
					},
					complete() {
						_self.loadding = false
					}
				});
			}
		}
	}
</script>

<style>
	.input-right {
		text-align: right;
	}
</style>
